package com.syq.job;

import com.rabbitmq.client.Channel;
import com.syq.constant.CacheConstants;
import com.syq.constant.RabbitMQConstants;
import com.syq.feign.CacheFeign;
import com.syq.util.JavaMailUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.IOException;
import java.util.Set;

@Component
@Slf4j
public class MonitorQueueMsgJob implements SimpleJob {

    @Autowired
    private Channel channel;

    @Resource
    private CacheFeign cacheFeign;

    @Autowired
    private JavaMailUtil javaMailUtil;

    @Override
    public void execute(ShardingContext shardingContext) {
        Set<String> keys = cacheFeign.keys(CacheConstants.CACHE_PREFIX_SMS_CHANNEL + "*");
        for (String key : keys){
            String channelId = key.substring(key.lastIndexOf(":") + 1);
            String queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + channelId;
            int messageCount = 0;
            try {
                channel.queueDeclare(queueName,true,false,false,null);
                messageCount = channel.queueDeclarePassive(queueName).getMessageCount();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if(messageCount > 5){
                log.info("[监控模块] {}队列中的消息，出现了消息堆积，消息的数量为：{}",queueName,messageCount);
                try {
                    javaMailUtil.sendMailForQueue(queueName,messageCount);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }else {
                log.info("[监控模块] {}队列中的消息，没有出现堆积问题！",queueName);
            }
        }
    }
}